package org.example.maven.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
public class RedisCommon {
    @Autowired
    public RedisTemplate redisTemplate;

    public <T> void setObjectKeyValue(final String key,final T value){
        redisTemplate.opsForValue().set(key, value);
    }

    public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit){
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    public <T> boolean checkCodeIsTure(final String key, final T value){
        // 1. 检查 key 是否存在
        if (!redisTemplate.hasKey(key)) {
            return false;
        }
        System.out.println("uuidd:"+key+" codee:"+redisTemplate.opsForValue().get(key));
        // 2. 获取 key 的值并比较
        T storedValue = (T) redisTemplate.opsForValue().get(key);
        redisTemplate.delete(key); // 无论是否匹配都删除验证码
        return Objects.equals(value, storedValue);
    }

    public <T> boolean checkHaveCode(final String key){
        return redisTemplate.hasKey(key);
    }

    // 存入整个列表
    public void setList(String key, List<?> list, final Integer timeout, final TimeUnit timeUnit) {
        redisTemplate.opsForList().rightPushAll(key, list);
        // 2. 设置过期时间（关键步骤！）
        redisTemplate.expire(key, timeout, timeUnit);
    }

    // 获取整个列表
    public <T> List<T> getList(String key) {
        return (List<T>) redisTemplate.opsForList().range(key, 0, -1);
    }

    //删除对应的键值对
    public Boolean deleteDataByKey(String key){
        return redisTemplate.delete(key);
    }



}
